<?php


namespace App\controller\app;


use app\common\Sign;
use app\common\Verify;
use App\model\UserModel;
use App\service\LoginRecord;
use support\Request;
use think\facade\Cache;
use think\facade\Db;
use Webman\Http\Response;
use app\service\Route;

class Login
{
    protected $app_id = 0;

    public function beforeAction(Request $request){
        $_app_id = $request->header('appid');
        if(isset($_app_id)){
            $this->app_id = $_app_id;
        }
        else{
            return error('1','app_id is null');
        }
    }

    /**
     * @Route(reqUrl="/app.web.login")
     */
    public function webLogin(Request $request){
        $token = input("token");
        $verify = new Verify(array("seKey"=>$token));
        if ($verify->check(input('code'))) {
            if(empty(input('username',null))){
                return error(0,"username is null");
            }
            if(empty(input('password',null))){
                return error(0,"password is null");
            }

            $client_ip = $request->getRealIp($safe_mode=true);
            $userObj = new UserModel([],$this->app_id);
            $user = $userObj->login(input('username'), input('password'),$client_ip);
            if($user instanceof Response){
                return $user;
            }
            else{
                $iat = time();
                $payload = [
                    'iss' => config('app.app_name'), //签发者
                    'iat' => $iat, //什么时候签发的
                    'exp' => $iat + 60*60*24*365, //过期时间()
                    'uid' => $user['user_id']
                ];
                $jwt = Sign::encode($payload, config('app.jwt_sign'));
                $user['access_token'] = $jwt;
                Cache::set('auth_'.$user['user_id'],$userObj->info($user['user_id']),60*60*24*365);
                return success($user,0,'登录成功');
            }
        }
        else{
            return error(1, "验证码错误");
        }
    }

    /**
     * @Route(reqUrl="/app.h5.login")
     */
    public function h5Login(Request $request){
        if(empty(input('username',null))){
            return error(1,"username is null");
        }
        if(empty(input('password',null))){
            return error(1,"password is null");
        }

        $client_ip = $request->getRealIp($safe_mode=true);
        $userObj = new UserModel([],$this->app_id);
        $user = $userObj->login(input('username'), input('password'),$client_ip);
        if($user instanceof Response){
            return $user;
        }
        else{
            $iat = time();
            $payload = [
                'iss' => config('app.app_name'), //签发者
                'iat' => $iat, //什么时候签发的
                'exp' => $iat + 60*60*24*365, //过期时间()
                'uid' => $user['user_id']
            ];
            $jwt = Sign::encode($payload, config('app.jwt_sign'));
            $user['access_token'] = $jwt;
            Cache::set('auth_'.$user['user_id'],$userObj->info($user['user_id']),60*60*24*365);
            return success($user,0,'登录成功');
        }
    }

    /**
     * @Route(reqUrl="/app.aptcha.login")
     */
    public function captchaLogin(Request $request){
        if(empty(input('userName',null))){
            return error(1,"账号不能为空");
        }
        if(empty(input('code',null))){
            return error(1,"验证码不能为空");
        }
        $code=input('code');
        $mobile=input('userName');
        $referrerId=input('referrerId',0);
        if($code==Cache::get($mobile.'_captcha')){
            $client_ip = $request->getRealIp($safe_mode=true);
            $userObj = new UserModel([],$this->app_id);
            $where=[];
            $where['mobile'] = $mobile;
            $where['useable'] = 1;
            $where['app_id'] = $this->app_id;
            $user = $userObj->where($where)->find();
            if($user){
                $user =  $userObj->info($user['user_id']);
                $iat = time();
                $payload = [
                    'iss' => config('app.app_name'), //签发者
                    'iat' => $iat, //什么时候签发的
                    'exp' => $iat + 60*60*24*365, //过期时间()
                    'uid' => $user['user_id']
                ];
                $jwt = Sign::encode($payload, config('app.jwt_sign'));
                $user['access_token'] = $jwt;
                Cache::set('auth_'.$user['user_id'],$userObj->info($user['user_id']),60*60*24*365);
                LoginRecord::add('login',$mobile,'success',$client_ip,$this->app_id);
                return success($user,0,'登录成功');
            }
            else{

                $_user=[];
                $_user['mobile'] = $mobile;
                $_user['referrer_id'] = $referrerId;
                $_user['level_id']=0;
                $_user['group_id'] = 0;
                $_user['useable'] = 1;
                $_user['app_id'] = $this->app_id;
                $_user['username'] = $mobile;
                $_user['avatar']=config('oss.OSS_DOMAIN').'/default_avatar.png';
                $_user['password']=md5($mobile);
                $_user['add_time']=time();

                Db::startTrans();
                try {

                    $user_id = $userObj->insertGetId($_user);

                    Db::commit();

                    $user =  $userObj->info($user_id);
                    $iat = time();
                    $payload = [
                        'iss' => config('app.app_name'), //签发者
                        'iat' => $iat, //什么时候签发的
                        'exp' => $iat + 60*60*24*365, //过期时间()
                        'uid' => $user['user_id']
                    ];
                    $jwt = Sign::encode($payload, config('app.jwt_sign'));
                    $user['access_token'] = $jwt;
                    Cache::set('auth_'.$user['user_id'],$userObj->info($user['user_id']),60*60*24*365);
                    LoginRecord::add('regOrLogin',$mobile,'success',$client_ip,$this->app_id);
                    return success($user,0,'登录成功');
                } catch (\Exception $e) {
                    Db::rollback();
                    LoginRecord::add('regOrLogin',$mobile,$e->getMessage(),$client_ip,$this->app_id);
                    return error(1,"登录失败");
                }
            }
        }
        else{
            return error(1,"验证码错误");
        }

    }

}